/*
 * Copyright (c) 2008 Kevin Wetzels
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */
package be.roam.jindy.xml;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

/**
 * Utility methods for dealing with XML.
 * 
 * @author Kevin Wetzels
 */
public class XmlUtils {

	/**
	 * Escapes the string and writes it to the writer.
	 * 
	 * @param writer
	 *            writer to write to
	 * @param string
	 *            string to escape
	 * @throws IOException
	 */
	public static void escape(Writer writer, String string) throws IOException {
		if (string == null) {
			return;
		}
		int length = string.length();
		for (int index = 0; index < length; ++index) {
			char character = string.charAt(index);
			if (character == '<') {
				writer.write("&lt;");
			} else if (character == '>') {
				writer.write("&gt;");
			} else if (character == '"') {
				writer.write("&quot;");
			} else if (character == '\'') {
				writer.write("&apos;");
			} else if (character == '&') {
				writer.write("&amp;");
			} else {
				writer.write(character);
			}
		}
	}

	/**
	 * Escapes the string.
	 * 
	 * @param string
	 *            string to escape
	 * @return the escaped string
	 * @throws IOException
	 */
	public static String escape(String string) throws IOException {
		if (string == null) {
			return null;
		}
		StringWriter writer = new StringWriter(string.length() + 30);
		escape(writer, string);
		return writer.toString();
	}

}
